package com.example.appcontact;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.example.base.BaseTabActivity;
import com.example.component.PopupContentView;
import com.example.component.QuickAction;
import com.example.connect.AsyncTask_Api;
import com.example.connect.AsyncTask_ApiListener;
import com.example.connect.CallApi;
import com.example.connect.ScreenStopper;
import com.example.database.DBManager;
import com.example.model.OutContacts;
import com.example.model.OutNotification;
import com.example.model.OutResult;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.SharedPreferencesDB;
import com.example.util.TokenUnableException;
import com.example.util.Util;

public class A003Contact extends TabActivity implements AsyncTask_ApiListener,
		OnClickListener, OnTabChangeListener {
	private int tabHeight = 80;
	private TabHost tabHost;
	private static final int TYPE_NOTIFICATION = 1;
	private static final int TYPE_GET_ALL_CONTACT = 2;
	private static final int TYPE_GET_MY_PROFILE = 3;
	private static final int TYPE_REJECT_REQUEST = 4;
	private static final int TYPE_ACCEPT_REQUEST = 4;
	private static final String TAG = "A003Contact";

	private Button iv_refresh, iv_information, iv_logout;
	private QuickAction quickAction;
	private String notificationId;
	private String emailLogged;
	private TextView tvTitle;
	private LinearLayout layout_top;
	private OutNotification outNotifications;
	private BaseTabActivity ac1, ac2;
	private PopupContentView temp;
	private DBManager mDB;
	private boolean isSettingDone = false;
	private String tabId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		initView();
	}

	@Override
	protected void onResume() {
		ac1 = (BaseTabActivity) getLocalActivityManager().getActivity(
				this.getString(R.string.devicecontacts));
		ac2 = (BaseTabActivity) getLocalActivityManager().getActivity(
				this.getString(R.string.BuchMeOcontacts));
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private void initView() {
		setContentView(R.layout.a003);
		this.layout_top = (LinearLayout) this
				.findViewById(R.id.a003_layout_top);
		this.iv_refresh = (Button) this.findViewById(R.id.a003_iv_refresh);
		this.iv_information = (Button) this
				.findViewById(R.id.a003_iv_information);
		this.tvTitle = (TextView) this.findViewById(R.id.a003_tv_text);
		this.iv_logout = (Button) this.findViewById(R.id.a003_iv_logout);
		this.iv_refresh.setOnClickListener(this);
		this.iv_information.setOnClickListener(this);
		this.iv_logout.setOnClickListener(this);

		tabHost = (TabHost) this.findViewById(android.R.id.tabhost);
		tabHost.setup();

		TabSpec spec1 = tabHost.newTabSpec(this
				.getString(R.string.devicecontacts));
		spec1.setIndicator(makeTabIndicator(this
				.getString(R.string.devicecontacts)));
		spec1.setContent(new Intent(this, A003DeviceContact.class));
		tabHost.addTab(spec1);

		TabSpec spec2 = tabHost.newTabSpec(this
				.getString(R.string.BuchMeOcontacts));
		spec2.setIndicator(makeTabIndicator(this
				.getString(R.string.BuchMeOcontacts)));
		spec2.setContent(new Intent(this, A003BuchMeOContact.class));
		tabHost.addTab(spec2);

		TabSpec spec3 = tabHost.newTabSpec(this.getString(R.string.setting));
		spec3.setIndicator(makeTabIndicator(this.getString(R.string.setting)));
		spec3.setContent(new Intent(this, A005MyProfile.class));
		tabHost.addTab(spec3);
		tabHost.setOnTabChangedListener(this);
        tabId  = getString(R.string.devicecontacts);
		
	}

	private TextView makeTabIndicator(String text) {
		TextView tabView = new TextView(this);
		LayoutParams lp3 = new LayoutParams(LayoutParams.WRAP_CONTENT,
				tabHeight, 1);
		lp3.setMargins(1, 0, 1, 0);
		tabView.setLayoutParams(lp3);
		tabView.setText(text);
		tabView.setTextColor(Color.WHITE);
		tabView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		tabView.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.tab_indicator));
		tabView.setPadding(13, 0, 13, 0);
		return tabView;
	}

	class PreExistingViewFactory implements TabContentFactory {
		private final View preExisting;

		protected PreExistingViewFactory(View view) {
			preExisting = view;
		}

		public View createTabContent(String tag) {
			return preExisting;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.a003_iv_refresh:
			refresh();
			break;
		case R.id.a003_iv_information:
			if(tabId.equalsIgnoreCase(getString(R.string.setting))){
				A005MyProfile myProfileActivity = (A005MyProfile) getLocalActivityManager().getActivity(
						this.getString(R.string.setting));
				myProfileActivity.btDoneClicked();
			}else{
				notificatisonClicked();
			}
			break;
		case R.id.a003_iv_logout:
			showLogout();
			break;

		default:
			break;
		}
	}
    private void notificatisonClicked(){
    	WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display disp = wm.getDefaultDisplay();
		int width = disp.getWidth();
		int height = disp.getHeight();
		int[] location = new int[2];
		layout_top.getLocationOnScreen(location);
		int mesuHeithTabhost = tabHeight;
		Rect anchorRect = new Rect(location[0], location[1], location[0]
				+ layout_top.getWidth(), location[1]
				+ layout_top.getHeight());
		Log.d("TAG", "height :" + height + "mesuHeithTabhost:  "
				+ mesuHeithTabhost + " anchorRect.bottom"
				+ anchorRect.bottom);
		height = height - (mesuHeithTabhost + anchorRect.bottom);
		emailLogged = new SharedPreferencesDB(this).getPrefEmail();
		quickAction = new QuickAction(this, height, width);
		temp = new PopupContentView(this, R.layout.popup_view, this,
				emailLogged);
		temp.showProcess();
		quickAction.addView(temp);
		quickAction.show(iv_information);
		doGetNotifications();
    }
	private void refresh() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_GET_ALL_CONTACT, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	public void callBackCancel(String notificationId) {
		this.notificationId = notificationId;
		if (quickAction != null)
			quickAction.dismiss();
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_REJECT_REQUEST, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}

	}

	public void callBackAccept(String notificationId) {
		this.notificationId = notificationId;
		if (quickAction != null)
			quickAction.dismiss();
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_ACCEPT_REQUEST, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	private void doGetNotifications() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_NOTIFICATION, 0, -1);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			showLogout();
		}
		return super.dispatchKeyEvent(event);
	}

	protected void showLogout() {
		Util.showDialog(this, R.string.logout, R.string.msg_logout,
				R.string.yes, R.string.no,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						SharedPreferencesDB db = new SharedPreferencesDB(A003Contact.this);
						boolean is_updated  = db.getPrefIsUpdateId();
						Intent intent = new Intent(getApplicationContext(),
								A002Login.class);
						setResult(1, intent);
						
						if(!is_updated){
							SharedPreferencesDB pre = new SharedPreferencesDB(A003Contact.this);
							String id = pre.getPrefId();
							openDatabase();
							mDB.deleteProfile(id);
						}
						finish();
					}
				}, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
	}

	@Override
	public Object callApi(int searchType, Object apidata) {
		if (searchType == TYPE_GET_ALL_CONTACT) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			OutContacts out  = new OutContacts();
			try{
				return CallApi.getContacts(this, data);
			}catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			}catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			}catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			}catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
			
			
		} else if (searchType == TYPE_NOTIFICATION) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			OutNotification out  = new OutNotification();
			try{
				return CallApi.getNotifications(this, data);
			}catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			}catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			}catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			}catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
			

		} else if (searchType == TYPE_ACCEPT_REQUEST) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			data.add(notificationId);
			OutResult out  = new OutResult();
			try{
				return CallApi.sendAcceptRequest(this, data);
			}catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			}catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			}catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			}catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		} else if (searchType == TYPE_REJECT_REQUEST) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			data.add(notificationId);
			OutResult out  = new OutResult();
			try{
				return CallApi.sendRejectRequest(this, data);
			}catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			}catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			}catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			}catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		}
		return null;
	}

	@Override
	public void finishApi(int searchType, Object apiresult) {
		if (searchType == TYPE_GET_ALL_CONTACT) {
			OutContacts data = (OutContacts) apiresult;
			ac1 = (BaseTabActivity) getLocalActivityManager().getActivity(
					this.getString(R.string.devicecontacts));
			ac2 = (BaseTabActivity) getLocalActivityManager().getActivity(
					this.getString(R.string.BuchMeOcontacts));
			if (ac1 != null)
				ac1.notificationRefresh(data.getList());
			else
				Log.e("AC1", "null");
			if (ac2 != null)
				ac2.notificationRefresh(data.getList());
			else
				Log.e("AC2", "null");
		} else if (searchType == TYPE_REJECT_REQUEST) {
			OutResult result = (OutResult) apiresult;
			if (result != null) {
				Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(this, "Please check again !!!",
						Toast.LENGTH_SHORT).show();
			}
		} else if (searchType == TYPE_ACCEPT_REQUEST) {
			OutResult result = (OutResult) apiresult;
			if (result != null) {
				Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(this, "Please check again !!!",
						Toast.LENGTH_SHORT).show();
			}
		} else { // TYPE_GET_NOTIFICATIONS
			try {
				outNotifications = (OutNotification) apiresult;
				
					if (outNotifications.getOutInfications().isEmpty()) {
						temp.showMessage("No Notifications ");
					} else {
						temp.showData(outNotifications);
					}
			} catch (Exception e) {
				e.printStackTrace();
				temp.showMessage("Please try again !");
			}
		}
	}

	@Override
	public void onTabChanged(String tabId) {
		this.tabId = tabId;
		Util.hideSoftKeyboard(getApplicationContext(), iv_information);
		changeTab3(tabId);
		if (tabId.equalsIgnoreCase(this.getResources().getString(
				R.string.BuchMeOcontacts))) {
			SharedPreferencesDB db = new SharedPreferencesDB(this);
			boolean isFirstStart = db.getPrefFirstStart();
			if (isFirstStart) {
				refresh();
				db.setPrefFirstStart(false);
			}

		}
	}
	public void changeTab3(String tabId){
		if (tabId.equalsIgnoreCase(this.getResources().getString(R.string.setting))) {
			this.iv_information.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_btn_header));
			String text  = this.getResources().getString(R.string.edit);
			if(isSettingDone){
				text  = this.getResources().getString(R.string.done);
			}
			iv_information.setText(text);
			tvTitle.setText(R.string.myprofile);
			this.iv_refresh.setVisibility(View.GONE);
		} else {
			if (tabId.equalsIgnoreCase(this.getResources().getString(R.string.BuchMeOcontacts))) 
				tvTitle.setText(R.string.BuchMeOcontacts);
			else 
				tvTitle.setText(R.string.devicecontacts);
			this.iv_refresh.setVisibility(View.VISIBLE);
			iv_information.setText("");
			this.iv_information.setBackgroundDrawable(
					this.getResources().getDrawable(R.drawable.bg_btn_notifi));
			
		}
			
		
	}
	public void setIsSettingDone(boolean is){
		this.isSettingDone = is;
		String text  = this.getResources().getString(R.string.edit);
		if(isSettingDone){
			text  = this.getResources().getString(R.string.done);
		}
		iv_information.setText(text);
	}
	public void openDatabase() {
		if (mDB == null) {
			mDB = new DBManager(this);
		}
		try {
			mDB.open();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void tokenExpride() {
		Util.startLogin(this);
	}
	
}
